﻿using System.Xml;

using octalforty.Syndication.Core;

namespace octalforty.Syndication.Core.Rss.Aggregators
{
    /// <summary>
    /// Aggregates RSS <c>&lt;item&gt;</c> elements.
    /// </summary>
    public class RssItemAggregator : RssAggregatorBase
    {
        /// <summary>
        /// Initializes a new instance of <see cref="RssItemAggregator"/> class.
        /// </summary>
        public RssItemAggregator()
        {
        }

        #region AggregatorBase Members
        /// <summary>
        /// Internal method, invoked from the implementation of 
        /// <see cref="RssAggregatorBase.InternalAggregate(XmlDocument,ref ISyndicationFeed)"/>.
        /// </summary>
        /// <param name="feedDocument"></param>
        /// <param name="rssFeed"></param>
        /// <remarks>
        /// The implementation must not invoke <see cref="IAggregator.Aggregate"/> 
        /// on the <see cref="AggregatorBase.NextAggregator"/>.
        /// </remarks>
        protected override void InternalAggregate(XmlDocument feedDocument, ref RssFeed rssFeed)
        {
            //
            // Loading items.
            XmlNodeList itemNodes = feedDocument.SelectNodes("/rss/channel/item");
            foreach(XmlNode itemNode in itemNodes)
                AggregateItem(itemNode, rssFeed);
        }
        #endregion

        /// <summary>
        /// Aggregates a single RSS item.
        /// </summary>
        /// <param name="itemNode"></param>
        /// <param name="rssFeed"></param>
        private static void AggregateItem(XmlNode itemNode, RssFeed rssFeed)
        {
            //
            // Loading item data. Start off with "required" elements.
            RssItem rssItem = new RssItem();

            rssItem.Title = GetNodeInnerText(itemNode, "./title");
            rssItem.Link = GetNodeInnerText(itemNode, "./link");
            rssItem.Description = GetNodeInnerText(itemNode, "./description");

            rssItem.Author = new RssPerson(string.Empty, GetNodeInnerText(itemNode, "./author"));
            rssItem.CommentsPageUrl = GetNodeInnerText(itemNode, "./comments");

            if(GetNodeInnerText(itemNode, "./pubDate") != string.Empty)
                rssItem.PublishedOn = ParseRfc1123DateTime(GetNodeInnerText(itemNode, "./pubDate"));

            rssFeed.Items.Add(rssItem);
        }
    }
}
